<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="queryParams" ref="queryParamsRef" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="手术申请时间" prop="surgeryApplyDate">
          <el-date-picker clearable
                          v-model="queryParams.surgeryApplyDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择手术申请时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="手术室" prop="surgeryName">
          <el-input
            v-model="queryParams.surgeryName"
            placeholder="请输入手术室"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手术间" prop="surgeryNoName">
          <el-input
            v-model="queryParams.surgeryNoName"
            placeholder="请输入手术间"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="病情说明" prop="patientCondition">
          <el-input
            v-model="queryParams.patientCondition"
            placeholder="请输入病情说明"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手术等级" prop="surgeryScale">
          <el-input
            v-model="queryParams.surgeryScale"
            placeholder="请输入手术等级"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          @click="handleAdd"
        >
          <template
            #icon>
            <i-ep-plus/>
          </template>
          新增
        </el-button>
      </el-col>
    </el-row>

    <el-table v-adaptive="500" :data="surgeryApplyList" :border="true" :stripe="true"
              highlight-current-row :header-cell-style="$headerCellStyle">
      <el-table-column label="手术申请时间" :align="'center'" prop="surgeryApplyDate" width="180">
        <template #default="scope">
          <span>{{ $parseTime(scope.row.surgeryApplyDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手术日期及时间" :align="'center'" prop="scheduledDate" width="180">
        <template #default="scope">
          <span>{{ $parseTime(scope.row.scheduledDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="手术室" prop="surgeryName"/>
      <el-table-column label="手术间" :align="'center'" prop="surgeryNoName"/>
      <el-table-column label="开单医生" :align="'center'" prop="applyUserName"/>
      <el-table-column label="开单科室" :align="'center'" prop="applyDeptName"/>
      <el-table-column label="麻醉方法" :align="'center'" prop="anesthesiaMethod">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['anesthesia_method']" :value="scope.row.anesthesiaMethod"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="手术状态" prop="surgeryStatus">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['surgery_status']" :value="scope.row.surgeryStatus"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="艾滋标记" prop="hivFlag">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['sys_yes_no']" :value="scope.row.hivFlag"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="乙肝标记" prop="hbvFlag">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['sys_yes_no']" :value="scope.row.hbvFlag"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="是否梅毒" prop="syphilisFlag">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['sys_yes_no']" :value="scope.row.syphilisFlag"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="是否洗手" prop="washHands">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['sys_yes_no']" :value="scope.row.washHands"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="备注信息" prop="remarks" width="200"/>
      <el-table-column :align="'center'" class-name="small-padding fixed-width" label="操作" width="100">
        <template #default="scope">
          <el-button
            type="success"
            @click="handleUpdate(scope.row)"
          >
            <template #icon>
              <i-ep-view/>
            </template>
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-drawer v-model="drawerVisible" :direction="'btt'" :show-close="false" size="90%">
      <template #header="{ close, titleId, titleClass }">
        <h4 :id="titleId" :class="titleClass">添加手术申请</h4>
        <el-button v-if="!formInfo.orderIds" type="success" @click="saveSurgery">
          保存
        </el-button>
        <el-button type="danger" @click="close">
          关闭
        </el-button>
      </template>
      <surgery-form ref="formRef" :patient-info="patientInfoThis"/>
    </el-drawer>
  </div>
</template>
<script lang="ts">
export default {
  name: "SurgeryApply"
}
</script>

<script setup lang="ts">
import {
  listSurgeryApply,
  delSurgeryApply, updateSurgeryApply, addSurgeryApply, getSurgeryApply
} from "@/api/surgery/surgeryApply.ts";
import {useDictStoreHook} from "@/store/modules/dict.ts";
import SurgeryForm from "@/views/surgery/apply/surgeryForm.vue";

const dictStore = useDictStoreHook();
const dictDataMap = ref(dictStore.isTypeGetData('surgery_status', 'incision_grade', 'anesthesia_method', 'sys_yes_no'))

const {proxy} = getCurrentInstance() as any;
const formRef = ref()
const drawerVisible = ref(false);
const queryParamsRef = ref()
const surgeryApplyList = ref([]);
const open = ref(false);
const showSearch = ref(true);

const props = defineProps({
  patientInfoThis: {
    type: Object,
    default: () => {
    },
  },
  inoroutFlag: {
    type: String,
    default: ""
  }
})


const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  surgeryId: "",
  clinicId: "",
  visitId: "",
  patientId: "",
  inoroutFlag: "",
  scheduledDate: "",
  surgeryApplyDate: "",
  surgeryRoomId: "",
  surgeryName: "",
  surgeryNoName: "",
  diagBeforeOperation: "",
  diagBeforeOperationCode: "",
  patientCondition: "",
  surgeryScale: "",
  isolationIndicator: "",
  applyUser: "",
  applyDeptId: "",
  anesthesiaMethod: "",
  emergencyFlag: "",
  surgeryBodyPart: "",
  provideWay: "",
  orgId: "",
  createDate: "",
  updateDate: "",
  remarks: "",
  hivFlag: "",
  hbvFlag: "",
  syphilisFlag: "",
  washHands: "",
  applyDeptName: "",
  applyUserName: "",
  updateByName: ""
})

/** 查询手术登记列表 */
function getList() {
  queryParams.value.inoroutFlag = props.inoroutFlag
  queryParams.value.visitId = props.patientInfoThis.visitId
  queryParams.value.clinicId = props.inoroutFlag === "1" ? "" : props.patientInfoThis.clinicId
  queryParams.value.visitId = props.patientInfoThis.visitId
  listSurgeryApply(queryParams.value).then((response: any) => {
    surgeryApplyList.value = response.data;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields()
  // proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  drawerVisible.value = true;
  nextTick(() => {
    formRef.value.reset()
  })
}


/** 删除按钮操作 */
function handleDelete(row) {
  ElMessageBox.confirm('是否确认删除数据项？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    delSurgeryApply(row.surgeryId).then(() => {
      getList();
      ElMessage.success("删除成功");
    })
  }).catch(() => {
  })
}

const formInfo = ref<any>({})
function handleUpdate(row) {
  drawerVisible.value = true;
  getSurgeryApply(row.surgeryApplyId).then((res: resType) => {
    formInfo.value = res.data
    nextTick(() => {
      formRef.value.getApplyForm(res.data)
    })
  })
}

function saveSurgery() {
  if (formRef.value && formRef.value.validateForm) {
    // 调用子组件的校验方法
    formRef.value.validateForm().then((valid: boolean) => {
      if (valid) {
        // 校验通过后，获取表单和手术列表数据
        if (formRef.value.getFormAndSurgeryData) {
          const {
            formData,
            surgeryApplyDetailList
          } = formRef.value.getFormAndSurgeryData();

          // 构建完整的保存数据
          const saveData = {
            ...formData,
            surgeryApplyDetailList // 添加手术详情列表到保存数据中
          };
          ElMessageBox.confirm('确定要开手术吗？',

            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          ).then(() => {
            saveData.visitId = props.patientInfoThis.visitId;
            saveData.patientId = props.patientInfoThis.patientId;
            saveData.clinicId = props.inoroutFlag === "1" ? "" : props.patientInfoThis.clinicId
            saveData.inoroutFlag = props.inoroutFlag;
            if (formData.surgeryApplyId) {
              updateSurgeryApply(saveData).then(() => {
                ElMessage.success("修改成功");
                getList();
                drawerVisible.value = false;
              }).catch((error) => {
                ElMessage.error("修改失败：" + (error?.message || '未知错误'));
              }).finally(() => {
                // 可以在这里添加完成后的处理
              });
            } else {
              addSurgeryApply(saveData).then(() => {
                ElMessage.success("新增成功");
                getList();
                drawerVisible.value = false;
              }).catch((error) => {
                ElMessage.error("新增失败：" + (error?.message || '未知错误'));
              }).finally(() => {
                // 可以在这里添加完成后的处理
              });
            }
          })
        }
      }
    });
  } else {
    // 如果子组件不存在或没有校验方法，则使用原来的校验逻辑
    (formRef.value as any).validate(valid => {
      if (valid) {
        // 原有的保存逻辑
        // 注意：这里可能无法获取到surgeryApplyDetailList数据
        ElMessage.warning('无法获取完整的手术详情数据，请升级组件后重试');
      }
    });
  }
}


getList();
</script>
